package com.lqk.fnandroid

import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Bundle
import android.util.Log
import androidx.room.Room
import com.lqk.fbridge.FlutterHelper
import com.lqk.fnandroid.db.EntityUserBean
import com.lqk.fnandroid.db.UserDatabase
import kotlin.concurrent.thread

class JetpackApplication : Application() {
    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
    }

    override fun onCreate() {
        super.onCreate()
        listenerLife()
        initDatabase()
        FlutterHelper.initFlutterHelper(this)
    }

    /**
     * 监听生命周期
     */
    private fun listenerLife() {
        this.registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {

            }

            override fun onActivityStarted(activity: Activity) {

            }

            override fun onActivityResumed(activity: Activity) {

            }

            override fun onActivityPaused(activity: Activity) {

            }

            override fun onActivityStopped(activity: Activity) {

            }

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {

            }

            override fun onActivityDestroyed(activity: Activity) {

            }
        })
    }

    /**
     * 初始化数据库
     */
    private fun initDatabase() {
        thread {
            val db = Room.databaseBuilder(this, UserDatabase::class.java, "jetpack-db").build()
            val l = db.userDao().queryUser()
            if (l.isEmpty()) {
                db.userDao().insertUser(EntityUserBean(1, userName = "LQK", userSex = true))
                db.userDao().insertUser(EntityUserBean(2, userName = "LQK1", userSex = true))
                db.userDao().insertUser(EntityUserBean(3, userName = "LQK2", userSex = true))
                db.userDao().insertUser(EntityUserBean(4, userName = "LQK3", userSex = true))
                db.userDao().insertUser(EntityUserBean(5, userName = "LQK4", userSex = true))
            } else {
                for (i in l){
                    Log.d("ROOM", "initDatabase: ${i.userId} : ${i.userName} : ${i.userSex}")
                }
            }
        }
    }
}